package com.foreknow.elm.dao.impl;

import com.foreknow.elm.dao.OrderdetailetDao;
import com.foreknow.elm.po.Food;
import com.foreknow.elm.po.Orderdetailet;
import com.foreknow.elm.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class OrderdetailetDaoImpl implements OrderdetailetDao {
    private Connection con = null;
    private PreparedStatement pst = null;
    private ResultSet rs = null;
    private int isRight = 0;
    @Override
    public int daoinsetorderdetailet(List<Orderdetailet> list) throws SQLException {
        int a = 0;
        StringBuffer stringBuffer = new StringBuffer("insert into orderdetailet(orderId,foodId,quantity) values(?,?,?)");
        try {
            con = DBUtil.getConnection();
            for (int b = 1;b < list.size();b++){
                stringBuffer.append(" ,(?,?,?)");
            }
            pst = con.prepareStatement(String.valueOf(stringBuffer));
            for(int i = 0;i < list.size();i++){
                pst.setInt(1+(i*3),list.get(i).getOrderId());
                pst.setInt(2+(i*3),list.get(i).getFoodId());
                pst.setInt(3+(i*3),list.get(i).getQuantity());
            }
            a = pst.executeUpdate();
        } finally {
            DBUtil.close(pst);
        }

        return a;
    }

    @Override
    public List<Orderdetailet> daoselectorderdetailet(Integer orderid) throws SQLException {
        List<Orderdetailet> list = new ArrayList<>();
        String sql = "select * from orderdetailet o,food f where o.foodid = f.foodid and orderId=?";
        try{
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql);
            pst.setInt(1,orderid);
            rs = pst.executeQuery();
            while (rs.next()){
                Orderdetailet orderdetailet = new Orderdetailet();
                orderdetailet.setOrderId(rs.getInt("orderId"));
                orderdetailet.setFoodId(rs.getInt("foodId"));
                orderdetailet.setQuantity(rs.getInt("quantity"));
                Food food = new Food();
                food.setFoodId(rs.getInt("foodId"));
                food.setFoodName(rs.getString("foodName"));
                food.setFoodExplain(rs.getString("foodExplain"));
                food.setFoodImg(rs.getString("foodImg"));
                food.setFoodPrice(rs.getDouble("foodPrice"));
                food.setBusinessId(rs.getInt("businessId"));
                food.setRemarks(rs.getString("remarks"));
                orderdetailet.setFood(food);
                list.add(orderdetailet);
            }
        }finally {
            DBUtil.close(rs,pst);
        }
        return list;
    }
}